package dx.util;

import org.jetbrains.annotations.Nullable;

import javax.servlet.http.HttpServletRequest;

/**
 * 将request里的值按key取出并转换成相应的类型
 * create by duanx 2021/2/2
 *@classname: HttpServletRequestUtil
 *@author: duanx
 *@date: 2021/2/2 23:57
 **/
public class HttpServletRequestUtil {

    /**将request里的key值转换成int类型
     * @param request 请求
     * @param key 键
     * @return int值
     */
    public static int getInt(HttpServletRequest request,String key){
        try {
            return Integer.decode(request.getParameter(key));
        }catch (Exception e){
            return -1;
        }
    }

    /**将request里的key值转换成long类型
     * @param request 请求
     * @param key 键
     * @return long值
     */
    public static long getLong(HttpServletRequest request,String key){
        try {
            return Long.decode(request.getParameter(key));
        }catch (Exception e){
            return -1L;
        }
    }


    /**将request里的key值转换成double类型
     * @param request 请求
     * @param key 键
     * @return double值
     */
    public static double getDouble(HttpServletRequest request,String key){
        try {
            return Double.parseDouble(request.getParameter(key));
        }catch (Exception e){
            return -1d;
        }
    }


    /**将request里的key值转换成boolean类型
     * @param request 请求
     * @param key 键
     * @return boolean值
     */
    public static boolean getBoolean(HttpServletRequest request,String key){
        try {
            return Boolean.parseBoolean(request.getParameter(key));
        }catch (Exception e){
            return false;
        }
    }


    /**将request里的key值转换成String类型
     * @param request 请求
     * @param key 键
     * @return String
     */
    @Nullable
    public static String  getString(HttpServletRequest request, String key){
        try {
            String result = String.valueOf(request.getParameter(key));
            if (result!=null){
                result =result.trim();
            }
            if ("".equals(result)){
                result = null;
            }
            return result;
        }catch (Exception e){
            return null;
        }
    }

}
